package com.tvein.sanguo.controller.FileLoader
{
	//flash
	import flash.net.LocalConnection;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLLoaderDataFormat;
	import flash.events.Event;
	//pureMVC
	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;
	//custom
	import com.tvein.sanguo.common.CommonConstants;
	import com.tvein.sanguo.model.ServerProxy;
	import com.tvein.sanguo.model.FilesProxy;
//
	public class FileDown extends SimpleCommand implements ICommand
	{
		private var serverData:ServerProxy;
		private var filesData:FilesProxy;
		
		override public function execute(notification:INotification) : void
		{
			serverData = facade.retrieveProxy( ServerProxy.NAME ) as ServerProxy;
			filesData = facade.retrieveProxy(FilesProxy.NAME) as FilesProxy;
			
			var testFile:Boolean = false;
			
			//check file exists
			for (var i:int = 0; i < filesData.filesArray.length; i++)
			{
				if (notification.getBody() == filesData.filesArray[i][0])
				{
					testFile = true;
					
					sendNotification(CommonConstants.FILELOADER, ["/fileloader -L", notification.getBody()]);
				}	
			}
				
			if (!testFile)
			{
				var params:Array = notification.getBody().split("|");
				
				if (serverData.p2pStatus)
				{
					var localConnection:LocalConnection = new LocalConnection();
					
					localConnection.send(CommonConstants.SYSTEM_CHANNEL, "console", ["/fileloader -D", [CommonConstants.GAME_CHANNEL, params[0], params[1]]]);
					
					localConnection = null;
				}
				else
				{
					var loader:URLLoader = new URLLoader();
					loader.dataFormat = URLLoaderDataFormat.BINARY;
					
					loader.addEventListener(Event.COMPLETE, function(evt:Event):void {_fileLoaded(evt, params[0] + "|" + params[1]);});
					loader.load(new URLRequest(srcSever() + params[0]));
				}
			}
		}
		
		private function srcSever():String
		{
			var i:int = Math.floor(Math.random() * serverData.srcServer.length());
			return (serverData.srcServer[i].@address);
		}
		
		private function _fileLoaded(evt:Event, fileInfo:String):void
		{
			evt.target.removeEventListener(Event.COMPLETE, _fileLoaded);
			filesData.filesDataAdd([fileInfo, evt.target.data]);
			
			sendNotification(CommonConstants.SYSTEM_CONSOLE, ["-loadFile", fileInfo.substr(fileInfo.lastIndexOf("/") + 1, fileInfo.length)]);
			
			sendNotification(CommonConstants.FILELOADER, ["/fileloader -L", fileInfo]);
		}
	}
}